from flask import Blueprint, jsonify, request, current_app, send_file, render_template
import requests
import base64
import os
import json
from routes.auth import login_required
from werkzeug.utils import secure_filename
import shutil
import time
import urllib.request
import urllib.parse

image = Blueprint('image', __name__)

# 百度API配置
API_KEY = "gMPbXgRrcnHUvhODFHnhjXvf"
SECRET_KEY = "t2qnLS8PzhS6RbaTLafMHWJWdJJ9hCGN"

# 允许的文件类型
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp'}

def ensure_dirs():
    """确保上传和审核目录存在"""
    dirs = {
        'upload': os.path.join('static', 'uploads', 'image'),
        'checked': os.path.join('static', 'uploads', 'image_checked')
    }
    for dir_path in dirs.values():
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
    return dirs

def allowed_file(filename):
    """检查文件类型是否允许"""
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def get_access_token():
    """获取百度API的access_token"""
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        "grant_type": "client_credentials",
        "client_id": API_KEY,
        "client_secret": SECRET_KEY
    }
    try:
        response = requests.post(url, params=params)
        result = response.json()
        if 'access_token' in result:
            return result['access_token']
        else:
            print(f"获取access_token失败: {result}")
            return None
    except Exception as e:
        print(f"获取access_token异常: {str(e)}")
        return None

@image.route('/list', methods=['GET'])
@login_required
def list_images():
    """获取所有图片列表"""
    dirs = ensure_dirs()
    
    # 获取未审核的图片
    unchecked_images = []
    for filename in os.listdir(dirs['upload']):
        if allowed_file(filename):
            unchecked_images.append({
                'filename': filename,
                'path': f"/static/uploads/image/{filename}",
                'status': 'unchecked'
            })
    
    # 获取已审核的图片
    checked_images = []
    for filename in os.listdir(dirs['checked']):
        if allowed_file(filename):
            # 读取审核结果
            result_file = os.path.join(dirs['checked'], f"{filename}.json")
            if os.path.exists(result_file):
                with open(result_file, 'r', encoding='utf-8') as f:
                    result = json.load(f)
                checked_images.append({
                    'filename': filename,
                    'path': f"/static/uploads/image_checked/{filename}",
                    'status': 'checked',
                    'result': result
                })
    
    return jsonify({
        'unchecked': unchecked_images,
        'checked': checked_images
    })

@image.route('/upload', methods=['POST'])
@login_required
def upload_image():
    """上传图片"""
    if 'image' not in request.files:
        return jsonify({'error': '未找到图片文件'}), 400
    
    files = request.files.getlist('image')
    uploaded_files = []
    
    dirs = ensure_dirs()
    
    for file in files:
        if file.filename == '':
            continue
            
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)  # 保持原始文件名
            filepath = os.path.join(dirs['upload'], filename)
            
            # 如果文件已存在，添加数字后缀
            base, ext = os.path.splitext(filename)
            counter = 1
            while os.path.exists(filepath):
                filename = f"{base}_{counter}{ext}"
                filepath = os.path.join(dirs['upload'], filename)
                counter += 1
                
            file.save(filepath)
            uploaded_files.append({
                'filename': filename,
                'path': f"/static/uploads/image/{filename}"
            })
    
    return jsonify(uploaded_files)

@image.route('/audit', methods=['POST'])
@login_required
def audit_image():
    """审核图片"""
    dirs = ensure_dirs()
    data = request.get_json()
    filename = data.get('filename')
    
    if not filename:
        return jsonify({'error': '未指定文件名'}), 400
        
    filepath = os.path.join(dirs['upload'], filename)
    if not os.path.exists(filepath):
        return jsonify({'error': '文件不存在'}), 404
        
    try:
        # 读取图片文件并转换为base64
        with open(filepath, 'rb') as f:
            image_data = f.read()
            image_base64 = base64.b64encode(image_data).decode('utf-8')
            
        # 获取access_token
        access_token = get_access_token()
        if not access_token:
            return jsonify({'error': '获取access_token失败'}), 500
            
        # 调用百度API
        url = f"https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token={access_token}"
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        data = {'image': image_base64}
        
        response = requests.post(url, headers=headers, data=data)
        result = response.json()
        
        # 保存审核结果
        new_filepath = os.path.join(dirs['checked'], filename)
        result_filepath = os.path.join(dirs['checked'], f"{filename}.json")
        
        # 移动文件到已审核目录
        shutil.move(filepath, new_filepath)
        
        # 保存审核结果
        with open(result_filepath, 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
            
        return jsonify(result)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@image.route('/export/<filename>', methods=['GET'])
@login_required
def export_result(filename):
    """导出审核结果"""
    dirs = ensure_dirs()
    result_file = os.path.join(dirs['checked'], f"{filename}.json")
    
    if not os.path.exists(result_file):
        return jsonify({'error': '审核结果不存在'}), 404
    
    # Flask 版本兼容处理
    try:
        return send_file(
            result_file,
            mimetype='application/json',
            as_attachment=True,
            attachment_filename=f"{filename}_audit_result.json"
        )
    except TypeError:
        return send_file(
            result_file,
            mimetype='application/json',
            as_attachment=True,
            download_name=f"{filename}_audit_result.json"
        )

@image.route('/delete/<filename>', methods=['DELETE'])
@login_required
def delete_image(filename):
    """删除图片"""
    dirs = ensure_dirs()
    
    # 检查未审核目录
    filepath = os.path.join(dirs['upload'], filename)
    if os.path.exists(filepath):
        os.remove(filepath)
        return jsonify({'message': '删除成功'})
        
    # 检查已审核目录
    filepath = os.path.join(dirs['checked'], filename)
    result_file = os.path.join(dirs['checked'], f"{filename}.json")
    
    if os.path.exists(filepath):
        os.remove(filepath)
        if os.path.exists(result_file):
            os.remove(result_file)
        return jsonify({'message': '删除成功'})
        
    return jsonify({'error': '文件不存在'}), 404

@image.route('/audit-all', methods=['POST'])
@login_required
def audit_all_images():
    """审核所有未审核的图片"""
    dirs = ensure_dirs()
    results = []
    
    for filename in os.listdir(dirs['upload']):
        if not allowed_file(filename):
            continue
            
        filepath = os.path.join(dirs['upload'], filename)
        try:
            # 读取图片文件并转换为base64
            with open(filepath, 'rb') as f:
                image_data = f.read()
                image_base64 = base64.b64encode(image_data).decode('utf-8')
                
            # 获取access_token
            access_token = get_access_token()
            if not access_token:
                results.append({
                    'filename': filename,
                    'error': '获取access_token失败'
                })
                continue
                
            # 调用百度API
            url = f"https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token={access_token}"
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
            data = {'image': image_base64}
            
            response = requests.post(url, headers=headers, data=data)
            result = response.json()
            
            # 保存审核结果
            new_filepath = os.path.join(dirs['checked'], filename)
            result_filepath = os.path.join(dirs['checked'], f"{filename}.json")
            
            # 移动文件到已审核目录
            shutil.move(filepath, new_filepath)
            
            # 保存审核结果
            with open(result_filepath, 'w', encoding='utf-8') as f:
                json.dump(result, f, ensure_ascii=False, indent=2)
                
            results.append({
                'filename': filename,
                'result': result
            })
            
        except Exception as e:
            results.append({
                'filename': filename,
                'error': str(e)
            })
            
    return jsonify(results)

@image.route('/export-all', methods=['GET'])
@login_required
def export_all_results():
    """导出所有审核结果"""
    dirs = ensure_dirs()
    all_results = {}
    
    # 获取所有已审核图片的结果
    for filename in os.listdir(dirs['checked']):
        if allowed_file(filename):
            result_file = os.path.join(dirs['checked'], f"{filename}.json")
            if os.path.exists(result_file):
                with open(result_file, 'r', encoding='utf-8') as f:
                    all_results[filename] = json.load(f)
    
    if not all_results:
        return jsonify({'error': '没有审核结果可导出'}), 404
    
    # 创建临时文件
    temp_file = os.path.join(dirs['checked'], 'all_results.json')
    with open(temp_file, 'w', encoding='utf-8') as f:
        json.dump(all_results, f, ensure_ascii=False, indent=2)
    
    # Flask 版本兼容处理
    try:
        return send_file(
            temp_file,
            mimetype='application/json',
            as_attachment=True,
            attachment_filename=f"audit_results_{int(time.time())}.json"  # 旧版本 Flask 使用
        )
    except TypeError:
        return send_file(
            temp_file,
            mimetype='application/json',
            as_attachment=True,
            download_name=f"audit_results_{int(time.time())}.json"  # 新版本 Flask 使用
        )

@image.route('/audit-url', methods=['POST'])
@login_required
def audit_url_image():
    """审核网络图片"""
    data = request.get_json()
    image_url = data.get('url')
    
    if not image_url:
        return jsonify({'error': '未提供图片URL'}), 400
        
    try:
        # 下载图片
        response = urllib.request.urlopen(image_url)
        image_data = response.read()
        
        # 转换为base64
        image_base64 = base64.b64encode(image_data).decode('utf-8')
        
        # 获取access_token
        access_token = get_access_token()
        if not access_token:
            return jsonify({'error': '获取access_token失败'}), 500
            
        # 调用百度API
        url = f"https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token={access_token}"
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        data = {'image': image_base64}
        
        response = requests.post(url, headers=headers, data=data)
        result = response.json()
        
        # 添加原始URL到结果中
        result['image_url'] = image_url
        
        return jsonify(result)
        
    except Exception as e:
        return jsonify({
            'error': f'处理图片时发生错误: {str(e)}',
            'conclusion': '处理失败',
            'conclusionType': 4
        }), 500

@image.route('/api-doc', methods=['GET'])
@login_required
def api_doc():
    """API文档页面"""
    return render_template('api_doc.html') 